package function;

import java.util.Enumeration;
import java.util.Hashtable;

import playlist.Crawler;
import tool.Mp3Browser;
import tool.Mp3Handler;

public class SearchFunction {

	private Crawler midlet;
	private Hashtable index = new Hashtable();

	public SearchFunction(Crawler midlet) {
		super();
		this.midlet = midlet;
	}

	public void setup() throws Throwable {
		// Setup performance = 1600 ms.

		new Mp3Browser(midlet).browse(new Mp3Handler() {

			public void handleNextMP3(String dir, String mp3) throws Throwable {
				String key = mp3.substring(0, 2).toLowerCase();
				SearchDatum entry = new SearchDatum(dir, mp3);

				if (!index.containsKey(key)) {
					index.put(key, entry);
				} else {
					SearchDatum current = (SearchDatum) index.get(key);
					if (current.getName().compareTo(mp3) >= 0) {
						// mp3 < current
						index.remove(key);
						index.put(key, entry);
					}
				}
			}
		});
	}

//	private void testPrintContents() {
//		int size = index.size();
//		int i = 10;
//		Enumeration keys = index.keys();
//		StringBuffer sb = new StringBuffer().append("DB Size:\n").append(size);
//
//		while ((i-- > 0) && (keys.hasMoreElements())) {
//			String key = (String) keys.nextElement();
//			SearchDatum datum = (SearchDatum) index.get(key);
//			sb.append("\nKey:\n" + key).append("\nDir:\n").append(
//					datum.getDir()).append("\nFile:\n").append(datum.getName())
//					.append("\n");
//		}
//		midlet.alert(new Throwable(sb.toString()));
//	}

	public SearchDatum find(String searchEntry) throws Throwable {
		SearchDatum datum = (SearchDatum) index.get(searchEntry);
		if (datum != null) {
			return datum;
		} else {
			return null;
		}
	}
}
